import { IAddress } from "@/type/index";
import { listAddress, updateAddress } from "@/api/index";
import { cache } from "@/util/index";
Page({
  data: {
    addressList: [] as IAddress[],
  },

  /**
   * 使用 onShow 是为了每次从编辑页返回时都能刷新列表
   */
  onShow() {
    this.getAddressList();
  },
  select(event) {
    const { id } = event.currentTarget.dataset;
    let info = this.data.addressList.find((i) => i._id === id);
    cache.set("address", info);
    wx.navigateBack();
  },
  async getAddressList() {
    const data = await listAddress();
    this.setData({
      addressList: data,
    });
  },

  handleAddNew() {
    wx.navigateTo({
      url: "../address_edit/index",
    });
  },

  handleEdit(event: WechatMiniprogram.TouchEvent) {
    const { id } = event.currentTarget.dataset;
    let info = this.data.addressList.find((i) => i._id === id);
    wx.navigateTo({
      url: `../address_edit/index?info=${JSON.stringify(info)}`,
    });
  },

  handleDelete(event: WechatMiniprogram.TouchEvent) {
    const { id } = event.currentTarget.dataset;
    wx.showModal({
      title: "确认删除",
      content: "您确定要删除这个地址吗？",
      success: async (res) => {
        if (res.cancel) return;
        const newList = this.data.addressList.filter((item) => item._id !== id);
        await updateAddress({
          id,
          status: false,
        });
        this.setData({ addressList: newList });
        wx.showToast({ title: "删除成功", icon: "none" });
      },
    });
  },
});
